package com.jml.juc.cas;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class ListNoSafeDemo {
    public static void main(String[] args) {
        listDemo();
        //setDemo();
        //mapDemo();
    }

    private static void mapDemo() {
        //Map<String, String> map = new HashMap<>();
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(Thread.currentThread().getName()+"\t" + map);
            }, String.valueOf(i)).start();
        }
    }

    private static void setDemo() {
        //HashSet<String> set = new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();
        /**
         底层就是CopyOnWriteArrayList包装的，
         add操作：获取CopyOnWriteArraySet的CopyOnWriteArrayList，遍历里面的数组，如果数组存在元素就不操作，
         如果不存在元素就调用CopyOnWriteArrayList的add方法
         */
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+"\t" + set);
            }, String.valueOf(i)).start();

        }
    }

    private static void listDemo() {
        //List<String> list = new ArrayList<>();
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                //先加lock锁，新建里一个数组，长度为老数组+1，然后把老数组拷贝到新数组，新数据放在最后，
                // 新数组替代老数组，其他线程，在操作的时候读的是老数组
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+"\t" + list);
            }, String.valueOf(i)).start();

        }
    }
}
